﻿using Leestar54.WeChat.WebAPI;
using Leestar54.WeChat.WebAPI.Modal;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace OznerOA.BLL
{
    public class WechatBLLAPI : BaseBLL
    {
        #region 全局变量
        //保存联系人信息
        private Dictionary<string, Contact> contactDict = new Dictionary<string, Contact>();
        //微信客户端对象
        private Client WechatClient = new Client();
        //获取联系人完成
        private bool BatchGetContactComplete = false;
        //获取联系人完成(包括公众号等)
        private bool GetContactComplete = false;
        //联系人获取完成事件
        public event EventHandler<TEventArgs<List<Contact>>> GetContactCompleteHandle;
        //单例的全局实例
        private static WechatBLLAPI WechatBLL = new WechatBLLAPI();
        #endregion
        #region 构造方法

        private WechatBLLAPI()
        {
            WechatClient.ExceptionCatched += Client_ExceptionCatched;
            WechatClient.GetContactComplete += WechatClient_GetContactComplete;
            WechatClient.BatchGetContactComplete += WechatClient_BatchGetContactComplete;
            WechatClient.LogoutComplete += WechatClient_LogoutComplete;
            WechatClient.LoginComplete += WechatClient_LoginComplete;
            WechatClient.CheckScanComplete += WechatClient_CheckScanComplete;
        }
        #endregion
        #region 微信扫描完成-保存图片
        private void WechatClient_CheckScanComplete(object sender, TEventArgs<Image> e)
        {
            LoginUserImage = e.Result;
        }
        #endregion
        #region 单例获取实例
        public static WechatBLLAPI GetInstance()
        {
            return WechatBLL;
        }
        #endregion
        #region 登录完成，保存登录用户
        private void WechatClient_LoginComplete(object sender, TEventArgs<User> e)
        {
            LoginUser = e.Result;
        }
        #endregion
        #region 微信退出
        private void WechatClient_LogoutComplete(object sender, TEventArgs<User> e)
        {
            logBLL.Info("您的微信已退出:" + e.Result.NickName);
        }
        #endregion
        #region 拉取联系人信息
        private void WechatClient_BatchGetContactComplete(object sender, TEventArgs<List<Contact>> e)
        {
            logBLL.Debug("拉取联系人信息，总数：" + e.Result.Count);
            foreach (var item in e.Result)
            {
                if (!contactDict.Keys.Contains(item.UserName))
                {
                    contactDict.Add(item.UserName, item);
                }
            }
            BatchGetContactComplete = true;
            GetContactAllComplate();
        }
        #endregion
        #region 获取联系人列表（包括公众号，联系人）
        private void WechatClient_GetContactComplete(object sender, TEventArgs<List<Contact>> e)
        {
            logBLL.Debug("获取联系人列表（包括公众号，联系人），总数：" + e.Result.Count);
            foreach (var item in e.Result)
            {
                if (!contactDict.Keys.Contains(item.UserName))
                {
                    contactDict.Add(item.UserName, item);
                }

                //联系人列表中包含联系人，公众号，可以通过参数做区分
                if (item.VerifyFlag != 0)
                {
                    //个人号
                }
                else
                {
                    //公众号
                }
            }
            this.GetContactComplete = true;
            GetContactAllComplate();
        }
        #endregion
        #region 所有联系人获取完成的方法
        private void GetContactAllComplate()
        {
            if (BatchGetContactComplete && GetContactComplete)
            {
                GetContactCompleteHandle?.Invoke(this, new TEventArgs<List<Contact>>(Contracts.Values.ToList<Contact>()));
            }
        }
        #endregion
        #region 刷新实例
        public void RefreshInstance()
        {
            this.WechatClient = new Client();
        }
        #endregion
        #region 启动微信客户端
        public void StartClient()
        {
            WechatClient.Start();
        }
        #endregion
        #region 获取微信客户端
        public Client GetWechatClient()
        {
            return WechatClient;
        }
        #endregion
        #region 微信客户端异常
        private void Client_ExceptionCatched(object sender, TEventArgs<Exception> e)
        {
            if (e.Result is GetContactException)
            {
                logBLL.Error("获取好友列表异常：" + e.Result.ToString());
                return;
            }

            if (e.Result is OperateFailException)
            {
                logBLL.Error("异步操作异常：" + e.Result.ToString());
                return;
            }

            logBLL.Error("异常：" + e.Result.ToString());
        }
        #endregion
        #region 退出微信
        public void logout()
        {
            if (LoginUser != null)
            {
                LoginUser = null;
                LoginUserImage = null;
                Contracts.Clear();
                WechatClient.LogoutAsync();
                WechatClient = new Client();
                logBLL.Info("已退出微信!");
            }
        }
        #endregion
        #region 登录用户属性
        public User LoginUser { get; set; }
        #endregion
        #region 联系人信息属性
        public Dictionary<string, Contact> Contracts
        {
            get { return contactDict; }
        }
        #endregion
        #region 登录用户图片信息
        public Image LoginUserImage { get; set; }
        #endregion
    }
}
